package com.backend.controller;

import com.backend.entity.Result;
import com.backend.entity.ResultCode;
import com.backend.entity.entity.Users;
import com.backend.entity.entity.WorkOrders;
import com.backend.service.RepairmanService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 作者:xuSen
 * 日期2025/7/20 10:57
 */
@RestController
@RequestMapping("/api/worker")
@Tag(name = "维修工模块接口")
public class RepairmanController {
    @Autowired
    private RepairmanService repairmanService;

    @GetMapping
    @Operation(summary = "获取所有维修工")
    public Result<List<Users>> getAllRepairman() {
        List<Users> allRepairman = repairmanService.getAllRepairman();
        allRepairman.forEach(repairman -> repairman.setPasswordHash(""));
        return Result.success(allRepairman);
    }

    @GetMapping("/order/{status}")
    @Operation(summary = "获取所有工单")
    public Result<List<WorkOrders>> getAllWorkOrder(@PathVariable("status") Integer status) {
        return Result.success(repairmanService.getWorkOrderByStatus(status));
    }

    @GetMapping("/order/detail/{orderId}")
    @Operation(summary = "获取工单详情")
    public Result<WorkOrders> getWorkOrderDetail(@PathVariable("orderId") Integer orderId) {
        return Result.success(repairmanService.getWorkOrderDetail(orderId));
    }

    @PostMapping("/order")
    @Operation(summary = "更新工单状态")// 传入工单号和状态
    public Result<String> updateWorkOrderStatus(@RequestBody WorkOrders workOrders) {
        if(workOrders.getStatus()==null||workOrders.getOrderId()==null)
            return Result.failure(ResultCode.FAILURE,"请检查工单号和状态！");
        repairmanService.updateWorkOrderStatus(workOrders.getOrderId(), workOrders.getStatus());
        return Result.success("修改成功");
    }

    @GetMapping("/order/repairman/{status}")
    @Operation(summary = "通过状态获取维修工的订单") //获取个人的工单
    public Result<List<WorkOrders>> getWorkOrderByStatusAndRepairId(@PathVariable("status") Integer status) {
        //获取id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long repairId= null;
        if(authentication!=null&&authentication.getPrincipal() instanceof Long &&authentication.getAuthorities().toString().contains("1")){
             repairId= (Long) authentication.getPrincipal();
        }else {
            return Result.failure(ResultCode.FAILURE,"该成员不是维修工！！！");
        }
        List<WorkOrders> list = repairmanService.getWorkOrderByStatusAndRepairId(status, repairId.intValue());
        return Result.success(list);
    }


}
